package org.example.school.controller;


import jakarta.servlet.http.HttpSession;
import org.apache.catalina.User;
import org.example.school.common.Context;
import org.example.school.common.Result;
import org.example.school.entity.Users;

import org.example.school.model.dto.GuardianProfileDTO;
import org.example.school.model.dto.StudentProfileDTO;
import org.example.school.model.dto.TeacherProfileDTO;
import org.example.school.model.dto.UserDTO;
import org.example.school.service.IParentsService;
import org.example.school.service.IStudentsService;
import org.example.school.service.ITeachersService;
import org.example.school.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private IUsersService usersService;
    @Autowired
    private IStudentsService studentsService;
    @Autowired
    private IParentsService parentsService;
    @Autowired
    private ITeachersService teachersService;

    /**
     * 用户登录接口
     *
     * @param user 包含用户名和密码的用户对象
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody UserDTO user, HttpSession session) {
        try {
            // 调用服务层进行登录验证
            Users loginUser = usersService.login(user.getUsername(), user.getPassword());
            if (loginUser.getStatus().equals(false)) {
                return Result.error("用户已经封禁");
            }
            if (loginUser != null) {
                // 将用户信息存储到session中
                session.setAttribute("userId", loginUser.getId());
                return Result.success(loginUser.getUserType());
            } else {
                return Result.error("用户名或密码错误");
            }
        } catch (Exception e) {
            return Result.error("登录失败: " + e.getMessage());
        }
    }

    /**
     * 用户注册接口
     *
     * @param user 包含注册信息的用户对象
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody UserDTO user) {
        try {
            boolean success = usersService.register(user);
            if (success) {
                return Result.success("注册成功");
            } else {
                // 更具体的错误应在Service层通过异常抛出，在此处捕获
                return Result.error("注册失败，用户名可能已存在");
            }
        } catch (Exception e) {
            return Result.error("注册失败: " + e.getMessage());
        }
    }

    /**
     * 用户登出接口
     *
     * @param session HTTP会话
     * @return 登出结果
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpSession session) {
        session.invalidate();
        return Result.success("登出成功");
    }


    /**
     * 获取当前用户的个人信息
     *
     * @return 个人信息 DTO
     */
    @GetMapping("/profile")
    public Result<?> getProfile() {
        Long userId = Context.getId();
        if (userId == null) {
            return Result.error("用户未登录");
        }
        Users currentUser = usersService.getById(userId);
        if (currentUser == null) {
            return Result.error("用户不存在");
        }
        String userType = currentUser.getUserType();

        if ("1".equals(userType)) { // 老师
            TeacherProfileDTO teacherProfile = teachersService.getTeacherProfile(userId);
            teacherProfile.setUsertype(userType);
            teacherProfile.setUserId(userId);
            return Result.success(teacherProfile);
        } else if ("2".equals(userType)) { // 学生
            StudentProfileDTO studentProfile = studentsService.getStudentProfile(userId);
            studentProfile.setUsertype(userType);
            return Result.success(studentProfile);
        } else if ("3".equals(userType)) { // 监护人
            GuardianProfileDTO parentProfile = parentsService.getGuardianProfile(userId);
            parentProfile.setUserId(userId);
            parentProfile.setUsertype(userType);
            return Result.success(parentProfile);
        } else if ("4".equals(userType)) {
            return Result.success(currentUser);
        } else {
            return Result.error("未知的用户类型");
        }
    }

}
